package com.example.sunsg.okhttptest;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.util.Log;
import android.view.View;
import android.widget.Button;

import com.breadtrip.R;
import com.example.sunsg.okhttptest.bean.Book;
import com.example.sunsg.okhttptest.bean.User;
import com.example.sunsg.okhttptest.service.ProcessSercice;

import java.lang.ref.WeakReference;

import io.reactivex.Flowable;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import rx.schedulers.Schedulers;

/**
 * @description 进程间通信  IPC
 */

public class ProcessServiceCommunicationActivity extends Activity implements View.OnClickListener {
    private MyHandler mHandler;
    private Messenger mMessenger;
    private Messenger mMessengerSend;
    private IMyAidlInterface mIMyAidlInterface;
    private IMyAidlInterfaceAddBook mIMyAidlInterfaceAddBook;
    private ITestInterface mITestInterface;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_process_service_communication);
        mHandler = new MyHandler(this);
        Button btnBind = (Button) findViewById(R.id.bind_serviece);
        btnBind.setOnClickListener(this);
        Button unBind = (Button) findViewById(R.id.unbind_serviece);
        unBind.setOnClickListener(this);
        Button btnSendData = (Button) findViewById(R.id.send_data);
        btnSendData.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.bind_serviece:
                Intent intent = new Intent(ProcessServiceCommunicationActivity.this, ProcessSercice.class);
                bindService(intent,connAddBook, Context.BIND_AUTO_CREATE);
                break;
            case R.id.send_data:
                mMessengerSend = new Messenger(mHandler);
                Message msg = Message.obtain(null,0);
                Bundle bundle = new Bundle();
                bundle.putString("data","client sunsg");
                msg.setData(bundle);
                msg.replyTo = mMessengerSend;
                try {
                    mMessenger.send(msg);
                } catch (RemoteException e) {
                    e.printStackTrace();
                }
                break;
            case R.id.unbind_serviece:
                unbindService(connAddBook);
                Flowable.just("djkf").subscribeOn(io.reactivex.schedulers.Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(new Consumer<String>() {
                    @Override
                    public void accept(String s) throws Exception {

                    }
                });
                break;
        }
    }

    @Override
    protected void onDestroy() {
        if(mIMyAidlInterfaceAddBook != null && mIMyAidlInterfaceAddBook.asBinder().isBinderAlive()){
            try {
                mIMyAidlInterfaceAddBook.unregisterListener(callBackAddBook);
            } catch (RemoteException e) {
                e.printStackTrace();
            }
            unbindService(connAddBook);
        }
        super.onDestroy();
    }

    /**
     * handler
     */
    class MyHandler extends Handler{
        private final WeakReference<ProcessServiceCommunicationActivity> mActiviy;
        public MyHandler(ProcessServiceCommunicationActivity activity){
            mActiviy = new WeakReference<ProcessServiceCommunicationActivity>(activity);
        }
        @Override
        public void handleMessage(Message msg) {
            if(mActiviy.get() != null){
                if(msg.what == 0){
                    Bundle bundle = msg.getData();
                    if(bundle != null){
                        bundle.containsKey("data");
                        Log.i("test","serveie return data = "+bundle.getString("data"));
                    }
                    Log.i("test","serveie return data = ");
                }
            }

        }
    }

    /**
     * service connect
     */
    ServiceConnection conn = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            mMessenger = new Messenger(service);
            Log.i("test","bind serveice success");
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            Log.i("test","unbind serveice success");
        }
    };

    ServiceConnection conn2 = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            Log.i("test","bind serveice success");
            mIMyAidlInterface = IMyAidlInterface.Stub.asInterface(service);

            try {
                User user = mIMyAidlInterface.getUser();
                mIMyAidlInterface.register(call);
                Log.i("test","user = "+user.toString());
            } catch (RemoteException e) {
                e.printStackTrace();
            }

        }

        @Override
        public void onServiceDisconnected(ComponentName name) {

        }
    };




    IMyAidlInterfaceCallBack call = new IMyAidlInterfaceCallBack() {
        @Override
        public void basicTypes(int anInt, long aLong, boolean aBoolean, float aFloat, double aDouble, String aString) throws RemoteException {

        }

        @Override
        public int getCurrentPresent() throws RemoteException {
            return 11;
        }

        @Override
        public int getCurentStatus() throws RemoteException {
            return 22;
        }

        @Override
        public IBinder asBinder() {
            return null;
        }
    };


    ServiceConnection connAddBook = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            mIMyAidlInterfaceAddBook = IMyAidlInterfaceAddBook.Stub.asInterface(service);
            Log.i("test","bind seccess");
            try {
                mIMyAidlInterfaceAddBook.registerLintener(callBackAddBook);
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            mIMyAidlInterfaceAddBook = null;
            Log.i("test","onServiceDisconnected");
        }
    };



    IMyAidlInterfaceAddBookCallBack callBackAddBook = new IMyAidlInterfaceAddBookCallBack.Stub() {
        @Override
        public void onNewBookArrice(Book book) throws RemoteException {
            Log.i("test","book = "+book.toString());
        }

    };

}
